package lion.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import lion.framework.core.conf.Config;
import lion.framework.core.conf.ConfigManager;

/**
 * @author lion
 * @email hl_0074@sina.com
 * @date 2014年5月16日
 */
public class OutputCachedResponse extends HttpServletResponseWrapper {

	private ByteArrayOutputStream baos;
	private PrintWriter writer;
	private ServletOutputStream sos;
	private String charset;

	public OutputCachedResponse(HttpServletResponse response) {

		super(response);

		Config config = ConfigManager.getConfig("framework");
		this.charset = config.getString("framework.sysencoding", "UTF-8");
		this.baos = new ByteArrayOutputStream();
		this.sos = new CacheServletOutputStream(baos);
		try {
			this.writer = new PrintWriter(new OutputStreamWriter(this.baos, charset), true);
		} catch (UnsupportedEncodingException e) {
		}
	}

	@Override
	public PrintWriter getWriter() {

		return this.writer;
	}

	@Override
	public ServletOutputStream getOutputStream() throws IOException {
		return this.sos;
	}

	public byte[] getContent() {

		close();
		return this.baos.toByteArray();
	}

	private void close() {

		this.writer.close();
		try {
			this.sos.close();
		} catch (IOException e) {
		}
	}

	public String getStringContent() {

		close();
		try {
			return this.baos.toString(charset);
		} catch (UnsupportedEncodingException e) {
		}
		return "";
	}
}
